package com.road2trip.gwt.client.tools;

import com.google.gwt.core.client.JavaScriptObject;

/*
 * Utility classe to make JSON request in GWT client
 * */
public class JSONRequestHelper {

	public interface JSONResponseHandler{
		public void onResponseReceived(JavaScriptObject json);
	}
	

	public static void get(String url, JSONResponseHandler handler){
		String callbackName = "callback" + handler.hashCode(); // unique ID for the request to allow multiple request 
		get(url + "&callback="+ callbackName, callbackName, handler);
	}

	private native static void get(String url, String callbackName, JSONResponseHandler handler) /*-{		
		//We insert Javascript in the DOM in order to make the request => bypass browser protect for cross site request  
		callback = function(j) {
			handler.@com.road2trip.gwt.client.tools.JSONRequestHelper$JSONResponseHandler::onResponseReceived(Lcom/google/gwt/core/client/JavaScriptObject;)(j);
		};
		$wnd[callbackName]=callback;
		var script = $wnd.document.createElement("script");
		script.setAttribute("type", "text/javascript");
		script.setAttribute("src", url);
		$wnd.document.getElementsByTagName("head")[0].appendChild(script);		
	}-*/;
	
	
}
